<template>
  <teleport to="body">
    <el-dialog
      v-model="dialogVisible"
      width="1100px"
      destroy-on-close
      class="field-dialog"
      :close-on-click-modal="false"
      :show-close="true"
      :append-to-body="true"
      :modal-append-to-body="true"
      :z-index="2000"
      top="5vh"
    >
      <template #header>
        <div class="dialog-title">
          <el-icon><Grid /></el-icon>
          <span>字段管理</span>
        </div>
      </template>

      <div class="field-container" v-loading="loading">
        <div class="tip-box">
          <el-icon><InfoFilled /></el-icon>
          <span>正确设置字段管理及相关属性会让大模型更好的理解您的数据集</span>
        </div>

        <div class="operation-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索字段"
            clearable
            style="width: 250px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <div class="buttons">
            <el-button type="warning" @click="syncFields" :loading="syncLoading">
              <el-icon><RefreshRight /></el-icon> 同步字段
            </el-button>
          </div>
        </div>

        <el-tabs v-model="activeTab" class="field-tabs">
          <el-tab-pane label="可见字段" name="visible">
            <el-table
              :data="visibleFields"
              border
              style="width: 100%"
              max-height="calc(100vh - 400px)"
            >
              <el-table-column type="expand">
                <template #default="scope">
                  <div class="field-detail">
                    <el-row :gutter="20">
                      <el-col :span="24">
                        <h4 class="detail-title">描述</h4>
                        <p>{{ scope.row.description || '暂无描述' }}</p>
                      </el-col>
                    </el-row>

                    <el-row :gutter="20" v-if="scope.row.stats">
                      <el-col :span="24">
                        <h4 class="detail-title">统计信息</h4>
                        <el-descriptions :column="4" border>
                          <el-descriptions-item label="非空值数">{{ scope.row.stats.non_null_count || 0 }}</el-descriptions-item>
                          <el-descriptions-item label="唯一值数">{{ scope.row.stats.unique_count || 0 }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.min !== undefined" label="最小值">{{ scope.row.stats.min }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.max !== undefined" label="最大值">{{ scope.row.stats.max }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.avg !== undefined" label="平均值">{{ scope.row.stats.avg }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.median !== undefined" label="中位数">{{ scope.row.stats.median }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.most_common" label="最常见值">
                            {{ (scope.row.stats.most_common || []).slice(0, 3).map(v => v.value).join(', ') }}
                          </el-descriptions-item>
                        </el-descriptions>
                      </el-col>
                    </el-row>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="name" label="字段名" width="120">
                <template #default="scope">
                  <el-tooltip :content="scope.row.original_name || scope.row.name" placement="top">
                    <span>{{ scope.row.name }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column prop="display_name" label="显示名称" width="140">
                <template #default="scope">
                  <el-input v-model="scope.row.display_name" placeholder="请输入显示名称" @blur="updateField(scope.row)" />
                </template>
              </el-table-column>

              <el-table-column prop="data_type" label="数据类型" width="120">
                <template #default="scope">
                  <el-tag :type="getDataTypeTagType(scope.row.data_type)">
                    {{ scope.row.data_type }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="semantic_type" label="语义类型" width="120">
                <template #default="scope">
                  <el-select v-model="scope.row.semantic_type" placeholder="请选择类型" @change="updateField(scope.row)">
                    <el-option-group
                      v-for="group in semanticTypeOptions"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-option-group>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column prop="description" label="描述" min-width="220">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.description"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入描述"
                    @blur="updateField(scope.row)"
                  />
                </template>
              </el-table-column>

              <el-table-column prop="visible" label="可见" width="80">
                <template #default="scope">
                  <el-switch v-model="scope.row.visible" @change="updateField(scope.row)" />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="不可见字段" name="hidden">
            <el-table
              :data="hiddenFields"
              border
              style="width: 100%"
              max-height="calc(100vh - 400px)"
            >
              <el-table-column type="expand">
                <template #default="scope">
                  <div class="field-detail">
                    <el-row :gutter="20">
                      <el-col :span="24">
                        <h4 class="detail-title">描述</h4>
                        <p>{{ scope.row.description || '暂无描述' }}</p>
                      </el-col>
                    </el-row>

                    <el-row :gutter="20" v-if="scope.row.stats">
                      <el-col :span="24">
                        <h4 class="detail-title">统计信息</h4>
                        <el-descriptions :column="4" border>
                          <el-descriptions-item label="非空值数">{{ scope.row.stats.non_null_count || 0 }}</el-descriptions-item>
                          <el-descriptions-item label="唯一值数">{{ scope.row.stats.unique_count || 0 }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.min !== undefined" label="最小值">{{ scope.row.stats.min }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.max !== undefined" label="最大值">{{ scope.row.stats.max }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.avg !== undefined" label="平均值">{{ scope.row.stats.avg }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.median !== undefined" label="中位数">{{ scope.row.stats.median }}</el-descriptions-item>
                          <el-descriptions-item v-if="scope.row.stats.most_common" label="最常见值">
                            {{ (scope.row.stats.most_common || []).slice(0, 3).map(v => v.value).join(', ') }}
                          </el-descriptions-item>
                        </el-descriptions>
                      </el-col>
                    </el-row>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="name" label="字段名" width="120">
                <template #default="scope">
                  <el-tooltip :content="scope.row.original_name || scope.row.name" placement="top">
                    <span>{{ scope.row.name }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column prop="display_name" label="显示名称" width="140">
                <template #default="scope">
                  <el-input v-model="scope.row.display_name" placeholder="请输入显示名称" @blur="updateField(scope.row)" />
                </template>
              </el-table-column>

              <el-table-column prop="data_type" label="数据类型" width="120">
                <template #default="scope">
                  <el-tag :type="getDataTypeTagType(scope.row.data_type)">
                    {{ scope.row.data_type }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="semantic_type" label="语义类型" width="120">
                <template #default="scope">
                  <el-select v-model="scope.row.semantic_type" placeholder="请选择类型" @change="updateField(scope.row)">
                    <el-option-group
                      v-for="group in semanticTypeOptions"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-option-group>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column prop="description" label="描述" min-width="220">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.description"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入描述"
                    @blur="updateField(scope.row)"
                  />
                </template>
              </el-table-column>

              <el-table-column prop="visible" label="可见" width="80">
                <template #default="scope">
                  <el-switch v-model="scope.row.visible" @change="updateField(scope.row)" />
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </teleport>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, RefreshRight, Grid, InfoFilled } from '@element-plus/icons-vue'
import { getDatasetFields, updateFieldMetadata, syncDatasetFields } from '@/api/dataset'

const props = defineProps({
  modelValue: Boolean,
  datasetId: [String, Number]
})

const emit = defineEmits(['update:modelValue'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 状态
const loading = ref(false)
const syncLoading = ref(false)
const fieldList = ref([])
const searchKeyword = ref('')
const activeTab = ref('visible')

// 语义类型选项
const semanticTypeOptions = [
  {
    label: '文本',
    options: [
      { label: '文本', value: 'text' },
      { label: '名称', value: 'name' },
      { label: '描述', value: 'description' },
      { label: '地址', value: 'address' },
      { label: '电子邮件', value: 'email' },
      { label: '电话', value: 'phone' },
      { label: 'URL', value: 'url' }
    ]
  },
  {
    label: '数值',
    options: [
      { label: '数值', value: 'number' },
      { label: '金额', value: 'currency' },
      { label: '百分比', value: 'percent' },
      { label: '评分', value: 'rating' }
    ]
  },
  {
    label: '日期时间',
    options: [
      { label: '日期', value: 'date' },
      { label: '时间', value: 'time' },
      { label: '日期时间', value: 'datetime' },
      { label: '年', value: 'year' },
      { label: '月', value: 'month' },
      { label: '日', value: 'day' }
    ]
  },
  {
    label: '地理位置',
    options: [
      { label: '国家', value: 'country' },
      { label: '省份', value: 'province' },
      { label: '城市', value: 'city' },
      { label: '纬度', value: 'latitude' },
      { label: '经度', value: 'longitude' }
    ]
  },
  {
    label: '其他',
    options: [
      { label: 'ID', value: 'id' },
      { label: '布尔值', value: 'boolean' },
      { label: '代码', value: 'code' },
      { label: '其他', value: 'other' }
    ]
  }
]

// 根据数据类型获取标签类型
const getDataTypeTagType = (dataType) => {
  const typeMap = {
    'string': 'success',
    'text': 'success',
    'varchar': 'success',
    'integer': 'primary',
    'int': 'primary',
    'bigint': 'primary',
    'float': 'primary',
    'double': 'primary',
    'decimal': 'primary',
    'date': 'warning',
    'datetime': 'warning',
    'timestamp': 'warning',
    'boolean': 'info'
  }
  return typeMap[dataType.toLowerCase()] || 'info'
}

// 过滤字段列表
const visibleFields = computed(() => {
  const fields = fieldList.value.filter(field => field.visible)
  if (!searchKeyword.value) {
    return fields
  }
  const keyword = searchKeyword.value.toLowerCase()
  return fields.filter(field =>
    field.name.toLowerCase().includes(keyword) ||
    (field.display_name && field.display_name.toLowerCase().includes(keyword)) ||
    (field.description && field.description.toLowerCase().includes(keyword))
  )
})

const hiddenFields = computed(() => {
  const fields = fieldList.value.filter(field => !field.visible)
  if (!searchKeyword.value) {
    return fields
  }
  const keyword = searchKeyword.value.toLowerCase()
  return fields.filter(field =>
    field.name.toLowerCase().includes(keyword) ||
    (field.display_name && field.display_name.toLowerCase().includes(keyword)) ||
    (field.description && field.description.toLowerCase().includes(keyword))
  )
})

// 获取字段列表
const fetchFields = async () => {
  if (!props.datasetId) return

  loading.value = true
  try {
    const re = await getDatasetFields(props.datasetId)
    const res = re.data
    if (Array.isArray(res)) {
      fieldList.value = res.map(field => ({
        ...field,
        display_name: field.display_name || '',
        semantic_type: field.semantic_type || 'other',
        visible: field.visible === '1' || (field.visible === true)
      }))
    } else {
      fieldList.value = []
    }
  } catch (error) {
    console.error('获取字段列表失败:', error)
    ElMessage.error('获取字段列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 更新字段
const updateField = async (field) => {
  try {
    const data = {
      display_name: field.display_name,
      description: field.description,
      semantic_type: field.semantic_type,
      visible: field.visible ? '1' : '0'
    }

    await updateFieldMetadata(props.datasetId, field.id, data)
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新字段失败:', error)
    ElMessage.error('更新字段失败: ' + (error.message || '未知错误'))
  }
}

// 同步字段
const syncFields = async () => {
  if (!props.datasetId) return

  syncLoading.value = true
  try {
    await syncDatasetFields(props.datasetId)
    ElMessage.success('字段同步成功')
    // 刷新字段列表
    await fetchFields()
  } catch (error) {
    console.error('同步字段失败:', error)
    ElMessage.error('同步字段失败: ' + (error.message || '未知错误'))
  } finally {
    syncLoading.value = false
  }
}

// 监听对话框可见性变化
watch(dialogVisible, (newVal) => {
  if (newVal && props.datasetId) {
    fetchFields()
  }
})

// 组件挂载时获取字段列表
onMounted(() => {

})
</script>

<style>
/* 全局样式，确保对话框组件显示正确 */
.el-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1999 !important;
  height: 100% !important;
  overflow: auto;
}
</style>

<style scoped>
.field-dialog {
  position: relative !important;
}

.field-dialog :deep(.el-dialog__header) {
  margin-bottom: 0;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.field-dialog :deep(.el-dialog__body) {
  padding: 0;
  overflow: hidden;
  max-height: calc(100vh - 200px);
}

.dialog-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.dialog-title .el-icon {
  margin-right: 8px;
  font-size: 18px;
  color: #409EFF;
}

.field-container {
  display: flex;
  flex-direction: column;
  padding: 15px;
  overflow: hidden;
}

.tip-box {
  margin-bottom: 15px;
  padding: 12px 15px;
  background-color: #ecf5ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  border-left: 4px solid #409EFF;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.tip-box .el-icon {
  margin-right: 10px;
  font-size: 18px;
  color: #409EFF;
}

.tip-box span {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.operation-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.buttons {
  display: flex;
  gap: 10px;
}

.field-detail {
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-title {
  margin: 10px 0;
  color: #606266;
  font-weight: bold;
}

.dialog-footer {
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
}

.field-tabs {
  margin-top: 15px;
}
</style>
